import { CallHandler, ExecutionContext, Injectable, NestInterceptor, Logger } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements NestInterceptor {
  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    const req = context.getArgByIndex(1).req;
    const now = Date.now();
    if (req.originalUrl == '/status') {
      return next.handle();
    }
    return next.handle().pipe(
      map(data => {
        // 请求地址: ${req.originalUrl}
        //   Method: ${req.method}
        //   IP: ${req.ip}
        const logFormat = `
          用户: ${JSON.stringify(req.user || '')}
          返回数据: ${JSON.stringify(data)}
          拦截器时间: ${Date.now() - now}ms
         `;
        Logger.debug(logFormat, '拦截器Interceptor', true);
        return {
          data: data,
          status: 0,
          message: 'success',
        }
      })
    );
  }
}
